<?php
class MysqlQuery
{
	public $_con;
	public $dbname;
	public $username;
	public $password;
	public $host;
	public $lib;

	public function __construct(){
		$this->lib=simplexml_load_file("../helper/db.xml");
		$dbname=$this->lib->dbname;
		$username=$this->lib->username;
		$password=$this->lib->password;
		$host=$this->lib->host;
		$this->conn=mysql_connect($host,$username,$password);
		if (!$this->conn) {
			die("连接失败".mysql_error());
		}

		mysql_query("set names utf8",$this->conn);
		mysql_select_db($dbname,$this->conn);
	}

	//查找一条记录
	public function GetOne($sql,$limited = false)
	{
		if($limited == true){
			$sql = trim($sql.' LIMIT 1');
		}

		$res=mysql_query($sql,$this->conn) or die(mysql_error());
		if($res !== false){
			$arr = [];
			$i = 0;
			$row = mysql_fetch_row($res);

			if($row !==false){
				while($row){
					$arr[$i++]=$row;
					return $arr[0];
				}
			}else{
				return false;
			}
		}else{
			return false;
		}
	}


	//插入语句
	public function Insert($table,$array){

		$key = '';
		$value = '';

		foreach($array as $k =>$v){
			$key .=$k.",";
			$value .="'".$v."',";
		}
		$klen = strlen($key);
		$vlen = strlen($value);
		$key = substr($key,0,$klen-1);
		$value = substr($value,0,$vlen-1);

		$sql = "INSERT INTO ".$table."(".$key.") VALUES(".$value.")";

		$b=mysql_query($sql,$this->conn) or die(mysql_error());
		if (!$b) {
			return 0;//失败
		}else{
			if (mysql_affected_rows($this->conn)>0) {
				return mysql_insert_id();# 表示执行成功
			}else{
				return -1;//表示没有行受到影响
			}
		}

	}

	//查询所有
	public function GetAll($sql)
	{
		$arr= array();
		$res=mysql_query($sql,$this->conn) or die(mysql_error());
		$i=0;
		//把$res=>$arr
		while ($row=mysql_fetch_assoc($res)) {
			$arr[$i++]=$row;
		}
		// 这里可以马上把$res关闭
		return $arr;

	}

	//执行增删改语句
	public function Execute($sql)
	{
		$b=mysql_query($sql,$this->conn) or die(mysql_error());
		if (!$b) {
			return 0;//失败
		}else{
			if (mysql_affected_rows($this->conn)>0) {
				return 1;# 表示执行成功
			}else{
				return 2;//表示没有行受到影响
			}
		}
	}

	//查语句
	function GetRow($sql)
	{
		$arr= array();
		$res=mysql_query($sql,$this->conn) or die(mysql_error());
		$i=0;
		//把$res=>$arr
		while ($row=mysql_fetch_row($res)) {
			$arr[$i++]=$row;
		}
		// 这里可以马上把$res关闭
		return $arr;
	}

	function GetAssoc($sql)
	{
		$arr= array();
		$res=mysql_query($sql,$this->conn) or die(mysql_error());
		$i=0;
		//把$res=>$arr
		while ($row=mysql_fetch_assoc($res)) {
			$arr[$i++]=$row;
		}
		// 这里可以马上把$res关闭
		return $arr;
	}

	//关闭连接的方法
	public function close_connect(){
		if (!empty($this->conn)) {
			mysql_close($this->conn);
		}
	}

}
